# !/usr/bin/python
# -*- coding: utf-8 -*-

from selenium import webdriver
import xlrd
import xlwt
import random

wb = xlrd.open_workbook(r'C:\Users\liuyuanting\Desktop\ua.xlsx')
sh = wb.sheet_by_index(0)
# 随机获取ua


# sh_ip = wb.sheet_by_index(1)
# # 随机获取ip
# ip_num = random.randint(1,sh.nrows-1)
# ip = sh_ip.cell_value(ip_num,1)
# print(ip)

wb2 = xlwt.Workbook()
sheet = wb2.add_sheet('cookie')
row = 1
list = ['sessionid', 'area', 'sessionip','ua']
for i in range(len(list)):
     sheet.write(0, i, list[i])

url = "https://www.autohome.com.cn/advice/201810/923804.html"
# 进入浏览器设置
options = webdriver.ChromeOptions()
# 设置中文
options.add_argument('lang=zh_CN.UTF-8')
# options.add_argument(('--proxy-server=http://' + ip))

for j in range(0,50):
    print(j)
    i = 1
    ua_num = random.randint(1, sh.nrows - 1)
    ua = sh.cell_value(ua_num, 0)
    print(ua)
    options.add_argument(ua)
    browser = webdriver.Chrome(chrome_options=options)
    while i < 100:
        # browser = webdriver.Chrome()
        browser.get(url)
        i += 1
    for cookie in browser.get_cookies():
        # print('%s  -- %s ' % (cookie['name'], cookie['value']))
        if cookie['name'] == 'sessionid':
            print("%s --- %s" % (cookie['name'], cookie['value']))
            sheet.write(row, 0, cookie['value'])
        if cookie['name'] == 'area':
            print("%s --- %s" % (cookie['name'], cookie['value']))
            sheet.write(row, 1, cookie['value'])
        if cookie['name'] == 'sessionip':
            print("%s --- %s" % (cookie['name'], cookie['value']))
            sheet.write(row, 2, cookie['value'])
    sheet.write(row, 3, ua)
    row += 1
    browser.quit()
    wb2.save('bb.xls')


